package net.sf.midollo.net.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class InetServer implements Runnable {

	protected final ServerSocket serverSocket;
	protected final AcceptHandler acceptHandler;
	protected Exception error;

	public InetServer(int localPort, AcceptHandler acceptHandler) throws IOException {
		this.serverSocket = new ServerSocket(localPort);
		this.acceptHandler = acceptHandler;
	}

	public Exception getError() {
		return this.error;
	}

	public void close() throws IOException {
		this.serverSocket.close();
	}

	public void run() {
		try {
			this.error = null;
			Socket clientSocket;
			while (true) {
				clientSocket = this.serverSocket.accept();
				this.acceptHandler.accept(clientSocket);
			}
		} catch (Exception e) {
			this.error = e;
		}
	}
}
